<?php
	class crud_company {
		function getAllCompany(){
			$start	= (isset($_REQUEST['start']))? $_REQUEST['start'] : 0;
			$limit	= (isset($_REQUEST['limit']))? $_REQUEST['limit'] : 10;
			$sql = "select 
							* 
					from company where 1=1 ";
			$sqlCount = "select 
							count(*) as total
					from company where 1=1 ";
			if (isset($_GET['query'])){
				$sql .= "and (
							`ID` like '%".$_GET['query']."%' or
							`COMPANY` like '%".$_GET['query']."%' or
							`ADDRESS` like '%".$_GET['query']."%' 
						)";
				$sqlCount .= "and (
							`ID` like '%".$_GET['query']."%' or
							`COMPANY` like '%".$_GET['query']."%' or
							`ADDRESS` like '%".$_GET['query']."%' 
						)";
			}
			$sql .= " order by `COMPANY` LIMIT ".$limit." OFFSET ".$start;
			$resultSql = Yii::app()->db->createCommand($sql)->queryAll();
			$resultCount = Yii::app()->db->createCommand($sqlCount)->queryAll();
			echo '{success:true,results: '.$resultCount[0]['total'].',rows:'.json_encode($resultSql).'}';
		}
		
		function insert(){
			$model = new Company;
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$codeCompany = 'CP' . Yii::app()->helper->numb_code(3,'company','ID');
				$model->ID = $codeCompany;
				$model->ADDRESS = $_POST['address-inputEl'];
				$model->COMPANY = $_POST['company-inputEl'];
				$model->save();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Insert Sukses","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Insert Gagal","code":"0"}]}';
			}
			echo $feedback;
		}
		
		function update(){
			$model = Company::model()->findByPk($_POST['id-inputEl']);
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$model->ADDRESS = $_POST['address-inputEl'];
				$model->COMPANY = $_POST['company-inputEl'];
				$model->save();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Update Sukses","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Update Gagal","code":"0"}]}';
			}
			echo $feedback;
		}
		
		function delete(){
			$model = Company::model()->findByPk($_POST['id']);
			$transaction = Yii::app()->db->beginTransaction();
			try {
				$model->delete();
				$transaction->commit();
				$feedback = '{"feedback":[{"message":"Company : '.$model->COMPANY.' Berhasil Dihapus","code":"1","ID":"'.$model->ID.'"}]}';
			} catch (Exception $e) {
				// echo $e;
				$transaction->rollback();
				$feedback = '{"feedback":[{"message":"Company : '.$model->COMPANY.' Gagal Dihapus","code":"0"}]}';
			}
			echo $feedback;
		}
	}
?>